const http = require('http')
const Koa = require('koa')
const favicon = require('koa-favicon');
const static = require('koa-static');
const session = require('koa-session-minimal')
const bodyParser = require('koa-bodyparser')

const _DBMySQL = require('./server/dbs/db-mysql')
const _mongoDB = require('./server/dbs/db-mongo')
initDB()

//日志
const logMiddleWare = require('./server/logger');
const logger = require('./server/logger/logger');

const config = require('./server/config/sysConf.json')

const indexRouter = require('./server/routers')

const app = new Koa()


app.use(favicon(`${__dirname}/public/favicon.ico`));

// or use absolute paths
app.use(static(`${__dirname}/public/`));

app.use(bodyParser())
// app.use(session())
app.use(logMiddleWare())

app.use(indexRouter.routes())

app.use(indexRouter.allowedMethods())

const server = http.createServer(app.callback()).listen(config.port);
// const server = https.createServer({
//   key: fs.readFileSync('./httpskey/server.key'),
//   cert: fs.readFileSync('./httpskey/server.crt')
// }, app).listen(port);
/**
 * Listen on provided port, on all network interfaces.
 */
server.on('error', onError);
server.on('listening', onListening);

/**
 * Event listener for HTTP server "error" event.
 */
function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
    logger.error(error);
  }

  let bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      logger.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      logger.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */
function onListening() {
  let addr = server.address();
  let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
  logger.info('Listening on ' + bind);
}

function initDB() {
  global._UltDB = new _DBMySQL({
    host: "192.168.1.3",
    user: "root",
    port: 3306,
    password: "atmd@dd_2015",
    database: "ultimate",
    charset: "utf8_general_ci"
  })

  global._WebDB = new _DBMySQL({
    host: "192.168.1.2",
    // host: "192.168.1.3",
    user: "root",
    port: 3306,
    password: "atmd@dd_2014",
    // password: "atmd@dd_2015",
    database: "songlist",
    charset: "utf8_general_ci"
  })

  global._SLMongo = new _mongoDB('mongodb://192.168.1.2:54188', 'songlist')
  global._ed2kMongo = new _mongoDB('mongodb://192.168.1.2:54188', 'verycd')
}